package com.li.forum.controller;

import com.li.forum.common.AppResult;
import com.li.forum.common.ResultCode;
import com.li.forum.config.AppConfig;
import com.li.forum.exception.ApplicationException;
import com.li.forum.model.Article;
import com.li.forum.model.Board;
import com.li.forum.model.User;
import com.li.forum.service.IArticleService;
import com.li.forum.service.IBoardService;
import jakarta.annotation.Resource;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpSession;
import lombok.NonNull;
import lombok.extern.slf4j.Slf4j;
import org.springframework.web.bind.annotation.*;

import java.util.ArrayList;
import java.util.List;


@Slf4j
@RestController
@RequestMapping("/article")
public class ArticleController {
    
    @Resource
    private IArticleService articleService;
    
    @Resource
    private IBoardService boardService;
    
    //发布新帖子
    @PostMapping ("/create")
    public AppResult create (HttpServletRequest request,
                             @RequestParam ("boardId") @NonNull Long boardId,
                             @RequestParam("title") @NonNull String title,
                             @RequestParam("content") @NonNull String content) {
        //校验用户是否禁言
        HttpSession session = request.getSession(false);
        User user = (User) session.getAttribute(AppConfig.USER_SESSION);
        if(user.getState() == 1){
            return AppResult.failed(ResultCode.FAILED_USER_BANNED);
        }
        
        //校验板块是否异常
        Board board = boardService.selectById(boardId.longValue());
        if(board == null || board.getDeleteState() == 1 || board.getState() == 1) {
            log.warn(ResultCode.FAILED_BOARD_BANNED.toString());
            throw new ApplicationException(AppResult.failed(ResultCode.FAILED_BOARD_BANNED));
        }
        
        //封装文章
        Article article = new Article();
        article.setUserId(user.getId());
        article.setBoardId(boardId);
        article.setTitle(title);
        article.setContent(content);
        articleService.create(article);
        return AppResult.success();
    }
    
    @GetMapping("/getAllByBoardId")
    public AppResult<List<Article>> getAllByBoardId(@RequestParam(value = "boardId", required = false) Long boardId){
        List<Article> articles;
        if(boardId == null){
            articles= articleService.selectAll();
        } else {
            articles = articleService.selectAllByBoardId(boardId);
        }
        if(articles == null) {
            articles = new ArrayList<>();
        }
        return AppResult.success(articles);
    }
    
    
    @GetMapping("/getDetails")
    public AppResult<Article> getDetails(HttpServletRequest request, @RequestParam("id") @NonNull Long id){
        HttpSession session = request.getSession(false);
        User user = (User)session.getAttribute(AppConfig.USER_SESSION);
        Article article = articleService.selectDetailById(id);
        //判断帖子存不存在
        if(article == null){
            log.warn(ResultCode.FAILED_ARTICLE_NOT_EXISTS.toString());
            throw new ApplicationException(AppResult.failed(ResultCode.FAILED_ARTICLE_NOT_EXISTS));
        }
        //判断是不是文章的作者，或者是管理员
        if(user.getId() == article.getUserId() || user.getIsAdmin() == 1){
            article.setIsEditable(true);
        }
        return AppResult.success(article);
    }
    
    @PostMapping("/modify")
    public AppResult modify(HttpServletRequest request, @RequestParam("id") @NonNull Long id,
                            @RequestParam("title") @NonNull String title,
                            @RequestParam("content") @NonNull String content){
        HttpSession session = request.getSession(false);
        User user = (User) session.getAttribute(AppConfig.USER_SESSION);
        //判断用户是否禁言
        if(user.getState() == 1){
            log.warn(ResultCode.FAILED_USER_BANNED.toString());
            throw new ApplicationException(AppResult.failed(ResultCode.FAILED_USER_BANNED));
        }
        //校验是否存在帖子
        Article article = articleService.selectById(id);
        if(article == null){
            log.warn(ResultCode.FAILED_ARTICLE_NOT_EXISTS.toString());
            return AppResult.failed(ResultCode.FAILED_ARTICLE_NOT_EXISTS);
        }
        //判断是不是文章的作者，或者是管理员
        if(user.getId() != article.getUserId() && user.getIsAdmin() != 1){
            log.warn(ResultCode.FAILED_FORBIDDEN.toString());
            return AppResult.failed(ResultCode.FAILED_FORBIDDEN);
        }
        //判断帖子是否可编辑
        if(article.getState() == 1 || article.getDeleteState() == 1){
            log.warn(ResultCode.FAILED_ARTICLE_BANNED.toString());
            return AppResult.failed(ResultCode.FAILED_ARTICLE_BANNED);
        }
        articleService.modify(id, title,content);
        log.info("帖子更新成功，userId:" + user.getId() + ", 帖子id：" + id);
        
        return AppResult.success();
    }
    
    @PostMapping("/thumbsUp")
    public AppResult thumbsUp(HttpServletRequest request, @RequestParam("id") @NonNull Long id){
        //校验用户状态
        HttpSession session = request.getSession(false);
        User user = (User) session.getAttribute(AppConfig.USER_SESSION);
        if(user.getState() == 1){
            log.warn(ResultCode.FAILED_USER_BANNED.toString());
            throw new ApplicationException(AppResult.failed(ResultCode.FAILED_USER_BANNED));
        }
        articleService.thumbsUpById(id);
        return AppResult.success();
    }
    
    @PostMapping("/deleteById")
    public AppResult deleteById(HttpServletRequest request, @RequestParam("id") @NonNull Long id){
        HttpSession session = request.getSession(false);
        User user = (User) session.getAttribute(AppConfig.USER_SESSION);
        //校验用户状态
        if(user.getState() == 1){
            log.warn(ResultCode.FAILED_USER_BANNED.toString());
            return AppResult.failed(ResultCode.FAILED_USER_BANNED);
        }
        //校验是否存在帖子
        Article article = articleService.selectById(id);
        if(article == null || article.getDeleteState() == 1){
            log.warn(ResultCode.FAILED_ARTICLE_NOT_EXISTS.toString());
            return AppResult.failed(ResultCode.FAILED_ARTICLE_NOT_EXISTS);
        }
        if(user.getId() != article.getUserId() && user.getIsAdmin() != 1){
            log.warn(ResultCode.FAILED_FORBIDDEN.toString());
            return AppResult.failed(ResultCode.FAILED_FORBIDDEN);
        }
        articleService.deleteById(id);
        
        return AppResult.success();
    }
    
    @GetMapping("/getAllByUserId")
    public AppResult<List<Article>> getAllByUserId (HttpServletRequest request ,
                                                   @RequestParam(value = "userId", required = false) Long userId) {
        // 如果UserId为空，那么从session中获取当前登录的用户Id
        if (userId == null) {
            // 获取Session
            HttpSession session = request.getSession(false);
            // 获取User对象
            User user = (User) session.getAttribute(AppConfig.USER_SESSION);
            userId = user.getId();
        }
        // 调用Service
        List<Article> articles = articleService.selectByUserId(userId);
        // 返回结果
        return AppResult.success(articles);
    }
}
